/*
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.agerasample.basicsample;

import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;

/**
 * This implements getting a list of usernames. A fake latency is added. The number of returned
 * usernames is controlled by a public static field, to allow us to write deterministic tests.
 *
 */
public class UsernamesFetcher {
    /**
     * Config constant that determines the number of users to return.
     * {@link #getUsernames(UsernamesCallback)} fires an error if this is negative.
     */
    public static final int NUMBER_OF_USERS = 4;

    /**
     * This method fakes getting a list of usernames from a server. It fires
     * {@link UsernamesCallback#setError} if {@link #NUMBER_OF_USERS} is negative. It simulates
     * server latency to return usernames.
     *
     * @param callback UsernamesCallback
     */
    public void getUsernames(final UsernamesCallback callback) {
        if (NUMBER_OF_USERS < 0) {
            callback.setError();
            return;
        }

        EventHandler eh = new EventHandler(EventRunner.getMainEventRunner());
        Runnable runnable =
                new Runnable() {
                    @Override
                    public void run() {
                        // Create a fake list of usernames
                        String name1 = "Joe";
                        String name2 = "Amanda";
                        final List<String> usernames = new ArrayList<String>();
                        SecureRandom  random = new SecureRandom();
                        for (int i = 0; i < NUMBER_OF_USERS; i++) {
                            int number = random.nextInt(50);
                            if (System.currentTimeMillis() % 2 == 0) {
                                usernames.add(name1 + number);
                            } else {
                                usernames.add(name2 + number);
                            }
                        }
                        callback.setUsernames(usernames);
                    }
                };

        // Simulate network latency
        eh.postTask(runnable, 2000);
    }

    public interface UsernamesCallback {
        void setError();

        void setUsernames(List<String> usernames);
    }
}
